package com.example.simpletodolist;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class ToDoListProvider extends ContentProvider {
	
	// Debug tag for the LogCat
	private static final String TAG = "ToDoListProvider";
	
	// A reference to the database wrapper class
	private ToDoListDatabase mDB;
	
	// Construct the URI that other components will use to access this 
	// content provider. 
	private static final String AUTHORITY = "com.example.simpletodolist.ToDoListProvider";
	public static final int TODOS = 100;
	public static final int TODO_ID = 110;
	
	private static final String TODOS_BASE_PATH = "todos";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + 
			"/" + TODOS_BASE_PATH);
	
	public static final String CONTENT_ITEM_TYPE = 
			ContentResolver.CURSOR_ITEM_BASE_TYPE + "/todo";
	public static final String CONTENT_TYPE = 
			ContentResolver.CURSOR_DIR_BASE_TYPE + "/todo";
	
	private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	static {
		sURIMatcher.addURI(AUTHORITY, TODOS_BASE_PATH, TODOS);
		sURIMatcher.addURI(AUTHORITY, TODOS_BASE_PATH + "/#", TODO_ID);
	}

	@Override
	public boolean onCreate() {
		mDB = new ToDoListDatabase(getContext());
		return true;
	}
	
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
		queryBuilder.setTables(ToDoListDatabase.TABLE_TODO);
		
		int uriType = sURIMatcher.match(uri);
		switch(uriType) {
		case TODO_ID:
			//queryBuilder.appendWhere(TodoListDatabase.KEY_ROWID + "=" +
			//		uri.getLastPathSegment());
			break;
		case TODOS:
			// no filter (get all)
			break;
		default:
			throw new IllegalArgumentException("Unknown URI");
		}
		
		Cursor cursor = 
				queryBuilder.query(mDB.getReadableDatabase(), projection, 
						selection, selectionArgs, null, null, sortOrder);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		
		return cursor;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int uriType = sURIMatcher.match(uri);
		SQLiteDatabase db = mDB.getWritableDatabase();
		int rowsAffected = 0;
		switch (uriType) {
		case TODOS: // delete all
			rowsAffected = db.delete(ToDoListDatabase.TABLE_TODO,
					selection, selectionArgs);
			break;
		case TODO_ID:
			String id = uri.getLastPathSegment();
			if (TextUtils.isEmpty(selection)) {
				rowsAffected = db.delete(ToDoListDatabase.TABLE_TODO,
						ToDoListDatabase.KEY_ROWID + "=" + id, null);
			} else {
				rowsAffected = db.delete(ToDoListDatabase.TABLE_TODO,
						selection + " and " + ToDoListDatabase.KEY_ROWID + "=" + id, 
						selectionArgs);
			}
			break;
		default:
			throw new IllegalArgumentException("Unknown or Invalid URI " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return rowsAffected;
	}
	


	@Override
	public String getType(Uri uri) {
		int uriType = sURIMatcher.match(uri);
		switch (uriType) {
		case TODOS:
			return CONTENT_TYPE;
		case TODO_ID:
			return CONTENT_ITEM_TYPE;
		default:
			return null;			
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		int uriType = sURIMatcher.match(uri);
		if (uriType != TODOS) {
			throw new IllegalArgumentException("Invalid URI for insert");
		}
		SQLiteDatabase db = mDB.getWritableDatabase();
		try {
			long newID = db.insertOrThrow(
					ToDoListDatabase.TABLE_TODO, null, values);
			if (newID > 0) {
				Uri newUri = ContentUris.withAppendedId(uri, newID);
				getContext().getContentResolver().notifyChange(uri, null);
				return newUri;
			} else {
				throw new SQLException("Failed to insert row into " + uri);
			}
		} catch (SQLiteConstraintException e) {
            Log.i(TAG, "Ignoring constraint failure.");
        } catch (Exception e) {
        	Log.i(TAG, e.getMessage());
        }
		
		return null;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		int uriType = sURIMatcher.match(uri);
		SQLiteDatabase db = mDB.getWritableDatabase();
		int rowsAffected = 0;
		
		switch(uriType) {
		case TODO_ID:
			String id = uri.getLastPathSegment();
			StringBuilder modSelection = new StringBuilder(
					ToDoListDatabase.KEY_ROWID + "=" + id);
			
			if (!TextUtils.isEmpty(selection)) 
				modSelection.append(" and " + selection);
			
			rowsAffected = db.update(ToDoListDatabase.TABLE_TODO, 
					values, modSelection.toString(), null);
			break;
		case TODOS:
			rowsAffected = db.update(ToDoListDatabase.TABLE_TODO, 
					values, selection, null);
		default:
			throw new IllegalArgumentException("Unknown or Invalid URI " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return rowsAffected;
	}
	

}
